package com.sqf.soft.service.impl;

import com.sqf.soft.dao.IUserDao;
import com.sqf.soft.entity.User;
import com.sqf.soft.service.IUserService;
import com.sqf.soft.utils.CommonUtils;
import com.sqf.soft.utils.MD5Util;
import com.sqf.soft.utils.ResultMap;
import com.sqf.soft.utils.SystemConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserService implements IUserService {

    private final IUserDao userDao;

    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    public UserService(IUserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public Map<String, Object> findUserByLogin(User user) {
        if (CommonUtils.isBlank(user.getUsername())) {
            return ResultMap.getObject(SystemConstant.USER_USERNAME_IS_BLANK);
        }
        if (CommonUtils.isBlank(user.getPassword())) {
            return ResultMap.getObject(SystemConstant.USER_PASSWORD_IS_BLANK);
        }
        user.setPassword(MD5Util.stringMD5(user.getPassword()));
        try {
            User u = userDao.findUserByLogin(user);
            if (u == null) {
                return ResultMap.getObject(SystemConstant.SELECT_RESULT_IS_NULL);
            }
            return ResultMap.getObject(u);
        } catch (Exception e) {
            log.error("UserService/findUserByLogin", e);
            return ResultMap.getObject(SystemConstant.SELECT_EXCEPTION);
        }
    }

    @Override
    public Map<String, Object> createUser(User user) {
        if (CommonUtils.isBlank(user.getUsername())) {
            return ResultMap.getObject(SystemConstant.USER_USERNAME_IS_BLANK);
        }
        if (CommonUtils.isBlank(user.getPassword())) {
            return ResultMap.getObject(SystemConstant.USER_PASSWORD_IS_BLANK);
        }
        user.setId(CommonUtils.createKeyId());
        user.setPassword(MD5Util.stringMD5(user.getPassword()));
        try {
            userDao.createUser(user);
            return ResultMap.getObject(user);
        } catch (Exception e) {
            log.error("UserService/createUser", e);
            return ResultMap.getObject(SystemConstant.INSERT_EXCEPTION);
        }
    }
}
